package com.newsystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.newsystem.MyUtils.CommonResult;
import com.newsystem.mapper.UserMapper;
import com.newsystem.pojo.User;
import com.newsystem.service.impl.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 使用者 前端控制器
 * </p>
 *
 * @author chenlitao
 * @since 2022-11-06
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserMapper userMapper;
    private final UserService userService;
    private final RedisTemplate redisTemplate;

    @ApiOperation("登录")
    @PostMapping("/login")
    public CommonResult<Object> login(String account,String password){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("account",account);
        User user = userMapper.selectOne(userQueryWrapper);
        if(user != null){
            if(user.getPassword().equals(password)){
                if(user.getStatue()==0){
                    return CommonResult.failed("此账号已经注销");
                }
                String token = UUID.randomUUID()+"";
                //存到redis
                redisTemplate.opsForValue().set(token,user, Duration.ofHours(2L));
                return CommonResult.success(user,token);
            }
        }
        return CommonResult.failed("账号或者密码错误");
    }

    @ApiOperation("通用的注册")
    @PutMapping("/register")
    public CommonResult<Object> register(String account,String password,int role,String phone){
        if(account == null || account.equals("")){
            return CommonResult.failed("账号不能为空");
        }
        if(password == null || password.equals("")){
            return CommonResult.failed("密码不能为空");
        }
        return userService.insterUser(account,password,role,phone);
    }

    @ApiOperation("获取用户的消息")
    @GetMapping("/getUserInfo")
    public CommonResult<Object> getUserInfo(String userId){
        return userService.selectUserInfo(userId);
    }

    @ApiOperation("注销自己账号")
    @DeleteMapping("/delete")
    public CommonResult<Object> delete(String userId){
        User user = userMapper.selectById(userId);
        if (user == null){
            return CommonResult.failed("此账号不存在");
        }
        if(user.getStatue()==0){
            return CommonResult.failed("此账号已经注销");
        }
        user.setStatue(0);
        if (userMapper.updateById(user) > 0){
            return CommonResult.success("注销成功");
        }
        return CommonResult.failed("注销失败");
    }

}

